﻿/**
*    @file:    widget.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2025-01-03  13:11
*/
#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QSettings>
#include <databasecenter.h>

#include <QCloseEvent>
#include <QDir>
#include <QProcess>
#include <daemonlog.h>
#include <daemonlogdialog.h>
#include <progressmanagedialog.h>
#include <settingdialog.h>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //    showMaximized();
    setWindowIcon(QIcon(":/res/img/ico/daemon-stop.ico"));
    QFile file(QCoreApplication::applicationDirPath() + "/StyleSheet/BlackAndBlue.qss");
    if (file.open(QFile::ReadOnly))
    {
        //QApplication::setStyle(file.readAll());
        setStyleSheet(file.readAll());
        file.close();
    }
    DatabaseCenter::getInstance();
    daemonStatus = false;
    autoStartDaemon = false;
    openScreenshot = false;
    initTrayIcon();
    initDataBase();
    initWorkThread();
    startMonitorThread();
    startScreenshotThread();

    initParam(); //初始化配置
    progressScreenshotThread->setOpenScreenshot(openScreenshot);
    if (autoStartDaemon)
    {
        startDaemonThread();
    }
}

Widget::~Widget()
{
    uninitWorkThread();
    uninitTrayIcon();
    DatabaseCenter::deleteInstance();
    delete ui;
}

void Widget::initTrayIconMenu()
{
    trayIconMenu = new QMenu(this);
    showAction = new QAction(QIcon(":/res/img/ico/favicon.ico"), "进程守护", this);
    connect(showAction, &QAction::triggered, this, &Widget::show);
    switchAction = new QAction(QIcon(":/res/img/ico/start.ico"), "启动守护", this);
    connect(switchAction, &QAction::triggered, this, &Widget::slot_switchDaemon);
    quitAction = new QAction(QIcon(":/res/img/png/exit.png"), "退出守护", this);
    connect(quitAction, &QAction::triggered, this, &Widget::slot_exit);

    trayIconMenu->addAction(showAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(switchAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
}

void Widget::initTrayIcon()
{
    initTrayIconMenu();
    trayIcon = new QSystemTrayIcon();
    connect(trayIcon, &QSystemTrayIcon::activated, this, &Widget::trayIconActivated);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setIcon(QIcon(":/res/img/ico/daemon-stop.ico"));
    trayIcon->setToolTip("进程守护");
    trayIcon->show();
}

void Widget::uninitTrayIcon()
{
    delete trayIcon;
}

void Widget::initDataBase()
{
    //本程序数据库初始化
    QSqlDatabase useDb = DatabaseCenter::getInstance()->getConnection();
    QSqlQuery useQuery(useDb);

    //进程表
    Progress progress;
    useQuery.exec(progress.generateCreateTableSql(useDb.driverName()));
    //守护日志表
    DaemonLog daemonLog;
    useQuery.exec(daemonLog.generateCreateTableSql(useDb.driverName()));

    DatabaseCenter::getInstance()->releaseConnection(useDb);
}

void Widget::initWorkThread()
{
    progressScreenshotThread = new ProgressScreenshotThread();
    qRegisterMetaType<QByteArray>("QByteArray");
    connect(progressScreenshotThread, &ProgressScreenshotThread::signal_progressScreenshotData, ui->progressListWidget, &ProgressListWidget::slot_progressScreenshotData);
    progressMonitorThread = new ProgressMonitorThread();
    qRegisterMetaType<QList<ProgressInfo>>("QList<ProgressInfo>");
    connect(progressMonitorThread, &ProgressMonitorThread::signal_progressInfoList, ui->progressListWidget, &ProgressListWidget::slot_progressInfoList);
    progressDaemonThread = new ProgressDaemonThread();
    connect(progressDaemonThread, &ProgressDaemonThread::signal_runStatus, this, &Widget::slot_daemonStatus);
    connect(progressMonitorThread, &ProgressMonitorThread::signal_progressInfoList, progressDaemonThread, &ProgressDaemonThread::slot_progressInfoList);
}

void Widget::uninitWorkThread()
{
    delete progressMonitorThread;
    delete progressDaemonThread;
    delete progressScreenshotThread;
}

void Widget::initParam()
{
    QSettings settings(QCoreApplication::applicationDirPath() + "/" + "config/service.ini", QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    autoStartDaemon = settings.value("workParam/autoStartDaemon", false).toBool();
    settings.setValue("workParam/autoStartDaemon", autoStartDaemon);

    openScreenshot = settings.value("workParam/openScreenshot", false).toBool();
    settings.setValue("workParam/openScreenshot", openScreenshot);
}

void Widget::startMonitorThread()
{
    progressMonitorThread->start();
}

void Widget::stopMonitorThread()
{
    progressMonitorThread->stop();
}

void Widget::startDaemonThread()
{
    progressDaemonThread->start();
}

void Widget::stopDaemonThread()
{
    progressDaemonThread->stop();
}

void Widget::startScreenshotThread()
{
    progressScreenshotThread->start();
}

void Widget::stopScreenshotThread()
{
    progressScreenshotThread->stop();
}

void Widget::restartProgram()
{
    QString restartToolPath = QCoreApplication::applicationDirPath() + "/DelayedRestartProgress.exe";
    qDebug() << restartToolPath;
    QStringList params;
    params << QString::number(5);
    params << QApplication::applicationFilePath();
    qDebug() << params;
    if (QFileInfo::exists(restartToolPath))
    {
        bool success = QProcess::startDetached(restartToolPath, params);
        if (success)
        {
            Sleep(2000);
            // 退出当前程序
            DWORD processId = GetCurrentProcessId();
            system(QString("taskkill /f /pid %1").arg(processId).toStdString().c_str());
        }
        else
        {
            qCritical() << "打开重启工具失败:" << restartToolPath;
        }
    }
    else
    {
        qCritical() << "找不到重启工具:" << restartToolPath;
    }
}

void Widget::slot_daemonStatus(bool isRun)
{
    daemonStatus = isRun;
    switchAction->setText(isRun ? "停止守护" : "启动守护");
    switchAction->setIcon(isRun ? QIcon(":/res/img/ico/stop.ico") : QIcon(":/res/img/ico/start.ico"));
    ui->switchDaemonBtn->setText(isRun ? "停止守护" : "启动守护");
    ui->switchDaemonBtn->setIcon(isRun ? QIcon(":/res/img/ico/stop.ico") : QIcon(":/res/img/ico/start.ico"));
    trayIcon->setIcon(isRun ? QIcon(":/res/img/ico/daemon-start.ico") : QIcon(":/res/img/ico/daemon-stop.ico"));
    setWindowIcon(isRun ? QIcon(":/res/img/ico/daemon-start.ico") : QIcon(":/res/img/ico/daemon-stop.ico"));
}

void Widget::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::DoubleClick)
    {
        show();
    }
}

void Widget::slot_showView()
{
    show();
}

void Widget::slot_switchDaemon()
{
    if (!daemonStatus)
    {
        startDaemonThread();
    }
    else
    {
        stopDaemonThread();
    }
}

void Widget::slot_exit()
{
    qApp->quit();
}

void Widget::on_progressMange_clicked()
{
    ProgressManageDialog *progressManageDialog = new ProgressManageDialog(this);
    progressManageDialog->exec();
    delete progressManageDialog;
}

void Widget::on_switchDaemonBtn_clicked()
{
    slot_switchDaemon();
}

void Widget::closeEvent(QCloseEvent *event)
{
    event->ignore();
    this->hide();
    trayIcon->showMessage(
        "进程守护",
        "进程守护已最小化到托盘，可以从系统托盘打开",
        QSystemTrayIcon::Information,
        2000);
}

void Widget::on_daemonLogBtn_clicked()
{
    qDebug() << __FUNCTION__ << "open";
    DaemonLogDialog *daemonLogDialog = new DaemonLogDialog(this);
    daemonLogDialog->exec();
    delete daemonLogDialog;
    qDebug() << __FUNCTION__ << "close";
}

void Widget::on_systemSetting_clicked()
{
    SettingDialog *settingDialog = new SettingDialog(this);
    if (settingDialog->exec() == QDialog::Accepted)
    {
        initParam();
        progressScreenshotThread->setOpenScreenshot(openScreenshot);
    }
}
